const arr = [32, 31, 29, 26, 20, 24, 35, 6, 25, 39, 13,
  33, 8, 38, 10, 18, 5, 3, 27, 21, 17, 34, 28, 14,
  12, 23, 7, 22, 16, 19, 37, 9, 2, 30, 11, 36, 4,
  15, 40, 1];


class Sort {

  constructor(arr) {
    const cvs = document.getElementById('cvs');
    this.ctx = cvs.getContext('2d');

    this.currentFrame = 0
    this.len = arr.length
    this.arr = arr
    this.m = parseInt(this.currentFrame / this.len)
    this.n = this.currentFrame % this.len
    this.animtate()
  }

  animtate() {
    this.update()
    this.render()
    if (this.currentFrame < this.len * this.len) {
      requestAnimationFrame(() => {
        this.animtate()
      })
    }
  }

  render() {
    this.ctx.clearRect(0, 0, 500, 500)
    this.ctx.beginPath();

    for (let i = 0; i < this.len; i++) {
      if ((i === this.m || i === this.n) && this.m > this.n) {
        this.ctx.fillStyle = 'yellow';
      } else {
        this.ctx.fillStyle = 'orange';
      }

      const x = 500 / this.len * i
      const h = this.arr[i] * 10
      const y = 500 - h
      const w = 10
      this.ctx.fillRect(x, y, w, h);
    }
    this.ctx.closePath();
  }

  update() {
    this.m = parseInt(this.currentFrame / this.len)
    this.n = this.currentFrame % this.len

    if (this.n > this.m) {
      return this.currentFrame++
    }

    const { m, n } = this
    if (arr[m] < arr[n]) {
      let tem = arr[n]
      arr[n] = arr[m]
      arr[m] = tem
    }
    this.currentFrame++
  }
}

new Sort(arr)


